package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constans.MqConstant;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.to.ware.WareStockStatusTo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/9/17 22:12
 */
@Slf4j
@Component
public class OrderWareMqListener {
    @Autowired
    OrderInfoService orderInfoService;
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConstant.EXCHANGE_DIRECT_WARE_ORDER,type = "direct",durable = "true",autoDelete = "false"),
            value = @Queue(value =MqConstant.WARE_ORDER_QUEUE,durable = "true",autoDelete = "false"),
            key = MqConstant.ROUTING_WARE_ORDER
    ))
    public void listenWareStock(Message message, Channel channel) throws IOException {
        try {
            String msg = new String(message.getBody());
            WareStockStatusTo wareStockStatusTo = JsonUtil.jsonToObject(msg, new TypeReference<WareStockStatusTo>() {
            });
            //修改订单状态
            orderInfoService.updateOrderStatusByStock(wareStockStatusTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("收到库存消息，更新订单状态成功 orderId：{}，status：{}", wareStockStatusTo.getOrderId(), wareStockStatusTo.getStatus());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
